<?php

class Admin_AtualizacaosistemaController extends App_Controller_Action
{
    
    private $_table     = 'ATUALIZACAO_SISTEMA';
    private $_pk        = 'ATS_ID';
    private $_order_col = 'ATS_DAT DESC, ATS_HOR ';
    private $_order     = 'DESC';
    private $_sta_col   = 'ATS_STA';
    private $obj        = '';
    private $form       = '';
    public  $dir        = 'public/upload/atualizacaosistema/';
    public  $_file_col  = 'ATS_FILE';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Atualizacaosistema;
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('elemform','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_list.js');
        
        $where = $this->_pk.' > 0';
        
        $stafiltro = $this->_getParam('stafiltro', '1'); 
        if($stafiltro != '') $where .= ' AND ATS_STA = ' . $stafiltro;
        $this->view->stafiltro  = $stafiltro;
        
        $itfiltro = $this->_getParam('itfiltro', ''); 
        if($itfiltro != '') $where .= ' AND ATS_NOM like "' . $itfiltro.'%"';
        $this->view->itfiltro = $itfiltro; 
        
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order.'';
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
        /*
        // ler arquivos de um diretório
        $path = "application/modules/admin/controllers/";
        $diretorio = dir($path); 
        echo "Lista de Arquivos do diretório '<strong>".$path."</strong>':<br />"; 
        while($arquivo = $diretorio -> read()){ 
            if($arquivo != '.' && $arquivo != '..'){
                echo $arquivo.' - '.date("d/m/Y H:i:s", filemtime($filename))."<br />"; 
            }
            
        } 
        $diretorio -> close();
        */       
    }
    
    
    public function editAction() {
       
        Zend_Loader::loadClass('imagem','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_form_pdr.js'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_atualizacaosistema.js');
        
        
       
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if ($this->form->isValid($formData)) {
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                    
                    $data = $this->form->getValues();
                    
                    unset($data[$this->_file_col]);
                    unset($data['Salvar']); 
                    unset($data['MAX_FILE_SIZE']);
                    
                    if ($id == 0){

                        $data['ATS_NOM'] = $_FILES[$this->_file_col]['name'];
                        $data['ATS_DAT'] = date('Y-m-d');
                        $data['ATS_HOR'] = date('H:i:s');
                        $data['ATS_STA'] = 1;
                        $this->db->insert($this->_table,$data);
                        $id = $this->db->lastInsertId();  
                        imagem::rename($id,$this->dir,$returnImg['filenew']);
                        
                        $arq = glob($this->dir.$id.'.*');
                        foreach($arq as $filetemp){
                            $file = file_get_contents($filetemp);
                            $sqls = explode(';', $file);
                            foreach($sqls as $key => $sql){
                                
                                $sql = trim($sql);
                                
                                if(strlen($sql) > 5){
     
                                    $arr = array(
                                        'ATS_ID' => $id,
                                        'ATC_SQL' => $sql,
                                    );
                                    $this->db->insert('ATUALIZACAO_CARREGADO',$arr);
                                }
                            }
                        }   
                        
                        $query = 'SELECT SQL_CACHE * FROM ATUALIZACAO_CARREGADO WHERE ATS_ID = '.$id.' ORDER BY ATC_ID';
                        $result = $this->db->fetchAll($query);
                        foreach($result as $row){

                            $this->db->query($row['ATC_SQL']);

                            $arr = array(
                                'ATS_ID' => $id,
                                'ATX_SQL' => $row['ATC_SQL'],
                            );
                            $this->db->insert('ATUALIZACAO_EXECUTADO',$arr);
                            
                            $this->db->delete('ATUALIZACAO_CARREGADO','ATC_ID = '.$row['ATC_ID']);
                            
                        }
                        
                        $query = 'SELECT SQL_CACHE count(*) as TOTAL FROM ATUALIZACAO_CARREGADO WHERE ATS_ID = '.$id;
                        $res = $this->db->fetchRow($query);
                        if($res['TOTAL'] > 0){
                            $this->db->update($this->_table,'ATS_STA = 2', $this->_pk.' = ' . $id);
                        }
   
                    }
                    else{
                        //$this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                    }
                    
                    $this->_helper->redirector('index'); 
                    
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo $ex->getMessage().'<br>';
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
            }  
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk .' = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->form->populate($data);
                
            }
        }
    }

    public function deleteAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            $data = array($this->_sta_col => 0);
            $ok = (bool) $this->db->update($this->_table,$data, $this->_pk .' = ' . $id);

        }
        
        echo json_encode(array('ok' => $ok));
    }
    
}

